package com.oraycn.esbasic.listeners;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.RectF;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView; 

/*
* 缩放图片
* */
public class ZoomImageListener implements View.OnTouchListener {
    ImageView imageView;
    private static final int NONE = 0;
    private static final int DRAG = 1;
    private static final int ZOOM = 2;
    private int mode = NONE;

    /**
     * 当前触摸点相对于屏幕的坐标
     */
    private float mCurrentInScreenX;
    private float mCurrentInScreenY;

    /**
     * 上一次触摸点相对于屏幕的坐标
     */
    private float mLastInScreenX;
    private float mLastInScreenY;
    /**
     * 触摸点按下时的相对于屏幕的坐标
     */
    private float mDownInScreenX;
    private float mUpInScreenX;
    private float mDownInScreenY;

    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();
    private int screenWidth, screenHeight;//屏幕宽高
    private float distance;
    private float preDistance;
    private PointF mid = new PointF();
    private Context mcontext;
    private int img_Width=0;
    private int img_Height=0;
    private float MAX_ZOOM_SCALE =4.0f, MIN_ZOOM_SCALE =0.8f;
    private float offsetScale = 1;
    private float offsetX, offsetY = 0;
    private View.OnClickListener onClickListener;

    public ZoomImageListener(Context context)
    {
        this.mcontext=context;
        //屏幕的宽高
        DisplayMetrics dm=  context.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;  //屏幕宽度
        screenHeight = dm.heightPixels;  //屏幕高度
    }

    /**
    * 设置单击事件
    * */
    public void setOnClickListener(View.OnClickListener onClickListener)
    {
        this.onClickListener=onClickListener;
    }

    /**
    *设置用于显示的ImageView
     * @param imageView （该ImageView为全屏显示） 必须scaleType="matrix"
    * */
    public void setImageView(ImageView imageView)
    {
        this.imageView=imageView;
    }

    /**
    * 设置图片的尺寸
    * @param width 图片的宽度
    * @param height 图片的高度
     * */
    public void setImgSize(int width, int height)
    {
        img_Width=width;
        img_Height=height;
        this.fitCenter();
    }


    public void setMAX_ZOOM_SCALE(float _maxScale)
    {
        this.MAX_ZOOM_SCALE =_maxScale;
    }
    public void setMIN_ZOOM_SCALE(float _minScale)
    {
        this.MIN_ZOOM_SCALE =_minScale;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ImageView view = (ImageView) v;
        mCurrentInScreenX=event.getRawX();
        mCurrentInScreenY=event.getRawY();

        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            //单个手指触摸
            case MotionEvent.ACTION_DOWN:
                mode = DRAG;
                mDownInScreenX=event.getRawX();
                mDownInScreenY=event.getRawY();
                break;
            //两指触摸
            case MotionEvent.ACTION_POINTER_DOWN:
                preDistance = getDistance(event);
                //当两指间距大于10时，计算两指中心点
                if (preDistance > 10f) {
                    mid = getMid(event);
                    savedMatrix.set(matrix);
                    mode = ZOOM;
                }
                break;
            case MotionEvent.ACTION_UP:
                if(mode==DRAG && !isMove()&&onClickListener!=null)
                {
                    this.onClickListener.onClick(view);
                }
                mode = NONE;
                mCurrentInScreenX=0;
                mCurrentInScreenY=0;
                mDownInScreenX=0;
                mDownInScreenY=0;
                mLastInScreenX=0;
                mLastInScreenY=0;
                center();  //回弹，令图片居中
                break;
            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;
            case MotionEvent.ACTION_MOVE:
                //当两指缩放，计算缩放比例
                if (mode == ZOOM) {
                    distance = getDistance(event);
                    if (distance > 10f) {
                        matrix.set(savedMatrix);
                        float scale = distance / preDistance;
                        offsetScale *= scale;
                        if (offsetScale < MIN_ZOOM_SCALE) {
                            offsetScale = MIN_ZOOM_SCALE;
                        } else if (offsetScale > MAX_ZOOM_SCALE) {
                            offsetScale = MAX_ZOOM_SCALE;
                        }
                        offsetX -= (scale - 1) * mid.x;//(scale-1)*iniViewRectF.width();
                        offsetY -= (scale - 1) * mid.y;//(scale-1)*iniViewRectF.height()
                        matrix.postScale(offsetScale, offsetScale, mid.x, mid.y);//缩放比例和中心点坐标
                    }
                }else if(mode==DRAG)//单指移动
                {
                    offsetX += mCurrentInScreenX - mLastInScreenX;
                    offsetY += mCurrentInScreenY - mLastInScreenY;
                    matrix.postTranslate(mCurrentInScreenX - mLastInScreenX,mCurrentInScreenY - mLastInScreenY);
                }
                break;
        }
        mLastInScreenX=event.getRawX();
        mLastInScreenY=event.getRawY();
        view.setImageMatrix(matrix);
        return true;
    }

    private boolean isMove()
    {
        //允许有10的偏差 在判断是否移动的时候
        if(Math.abs(mDownInScreenX - mCurrentInScreenX) <= 10 && Math.abs(mDownInScreenY - mCurrentInScreenY) <= 10 ){
            return false;
        }else{
            return true;
        }
    }

    /*获取两指之间的距离*/
    private float getDistance(MotionEvent event) {
        float x = event.getX(1) - event.getX(0);
        float y = event.getY(1) - event.getY(0);
        float distance = (float) Math.sqrt(x * x + y * y);//两点间的距离
        return distance;
    }

    /*使图片居中*/
    private void center() {
        Matrix m = new Matrix();
        m.set(matrix);
        //绘制图片矩形
        //这样rect.left，rect.right,rect.top,rect.bottom分别就就是当前屏幕离图片的边界的距离
        RectF rect = new RectF(0, 0, img_Width, img_Height);
        m.mapRect(rect);
        float height = rect.height();
        float width = rect.width();
        float deltaX = 0, deltaY = 0;

        //获取ActionBar的高度
        int actionBarHeight = 0;
        //全屏则不用计算ActionBar的高度
//        TypedValue tv = new TypedValue();
//        if (activity.getBaseContext().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
//            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, activity.getBaseContext().getResources().getDisplayMetrics());
//        }
        //计算Y到中心的距离
        if (height < screenHeight) {
            deltaY = (screenHeight - height) / 2 - rect.top - actionBarHeight;
        } else if (rect.top > 0) {
            deltaY = -rect.top;
        } else if (rect.bottom < screenHeight) {
//            deltaY = imageView.getHeight() - rect.bottom;
            deltaY=screenHeight-rect.bottom;
        }
        //计算X到中心的距离
        if (width < screenWidth) {
            deltaX = (screenWidth - width) / 2 - rect.left;
        } else if (rect.left > 0) {
            deltaX = -rect.left;
        } else if (rect.right < screenWidth) {
            deltaX = screenWidth - rect.right;
        }
        offsetX += deltaX;
        offsetY += deltaY;
        matrix.postTranslate(deltaX, deltaY);
    }
    /*取两指的中心点坐标*/
    public static PointF getMid(MotionEvent event) {
        float midX = (event.getX(1) + event.getX(0)) / 2;
        float midY = (event.getY(1) + event.getY(0)) / 2;
        return new PointF(midX, midY);
    }

    private void fitCenter()
    {
        if(this.imageView==null)
        {
            return;
        }
        float wCoef = screenWidth / (float)this.img_Width;
        float hCoef = screenHeight /(float)this.img_Height;
        RectF rect ;
        if(wCoef==hCoef)
        {
            rect=new RectF(0, 0, img_Width, img_Height);
        }
        else if(wCoef<hCoef)
        {
            int newHeight=(int)(wCoef*this.img_Height);
            rect=new RectF(0,(screenHeight-newHeight)/2,screenWidth,newHeight+(screenHeight-newHeight)/2);
        }
        else {
            int newWidth=(int)(hCoef*this.img_Width);
            rect=new RectF((screenWidth-newWidth)/2,0,newWidth+(screenWidth-newWidth)/2,screenHeight);
        }
        Matrix m= new Matrix();
        m.set(matrix);
        matrix.reset();
        //绘制图片矩形
        //这样rect.left，rect.right,rect.top,rect.bottom分别对应着view的左上顶点的横坐标、左上顶点的纵坐标、右下顶点的横坐标、右下顶点的纵坐标），
        matrix.setRectToRect(new RectF(0,0,img_Width,img_Height),rect, Matrix.ScaleToFit.CENTER);
        imageView.setImageMatrix(matrix);
    }

    /**
    * 图像居中
    * */
    public void setCenter()
    {
        if(this.imageView==null)
        {
            return;
        }
        this.center();
        imageView.setImageMatrix(matrix);
    }
}
